package com.zifeng.study.springbootredis.controller;

import com.zifeng.study.springbootredis.service.RedisSecKillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;

/**
 * @author 吴梓锋
 * @version 1.0.0
 * @date 2022/05/23 11:13:24
 * @description redis测试controller
 */
@RestController
@Slf4j
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    RedisSecKillService redisSecKillService;

    @PostMapping("/seckill")
    public ResponseEntity<String> secKill(@RequestBody HashMap<String, String> body) {
        try {
            // 这里便于测试，如果接口请求没有提供userId则服务端生成
            String userId = ObjectUtils.isEmpty(body.get("userId")) ? UUID.randomUUID().toString().trim().replaceAll("-", "") : body.get("userId");
            String result = redisSecKillService.secKill(body.get("productKey"), userId);
            log.info("userId={}, result={}", userId, result);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("抢购失败!" + e.getMessage());
        }

    }

    @PostMapping("/init/product/count")
    public ResponseEntity<String> initProductCount(@RequestBody HashMap<String, String> body) {
        try {
            redisSecKillService.initProductCount(body.get("productKey"), body.get("productCount"));
            return ResponseEntity.ok("初始化库存成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("初始化库存失败！" + e.getMessage());
        }
    }

}
